package com.iotechn.microunimall.shopping.service.biz;

import com.iotechn.microunimall.core.Const;
import com.iotechn.microunimall.core.exception.ServiceException;
import com.iotechn.microunimall.data.starter.compent.CacheComponent;
import com.iotechn.microunimall.shopping.api.service.biz.CollectBizService;
import com.iotechn.microunimall.shopping.mapper.CollectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/11/11
 * Time: 21:30
 */
@Service("collectBizService")
public class CollectBizServiceImpl implements CollectBizService {

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private CacheComponent cacheComponent;

    public static final String CA_USER_COLLECT = "CA_USER_COLLECT_";

    @Override
    public Boolean getCollectBySpuId(Long spuId, Long userId) throws ServiceException {
        boolean hasKey = cacheComponent.hasKey(CA_USER_COLLECT + userId);
        if (!hasKey) {
            //若没有Key，则添加缓存
            List<String> spuIds = collectMapper.getUserCollectSpuIds(userId);
            if (CollectionUtils.isEmpty(spuIds)) {
                //redis set不能为空
                spuIds.add("0");
            }
            cacheComponent.putSetRawAll(CA_USER_COLLECT + userId, spuIds.toArray(new String[0]), Const.CACHE_ONE_DAY);
        }
        return cacheComponent.isSetMember(CA_USER_COLLECT + userId, spuId + "");
    }
}
